﻿#include "chatList.h"
#include <iostream>

using namespace std;

// 构造函数实现
ChatIist::ChatIist() {
	// 使用try-catch语句来捕获异常,增加异常处理机制
	try {
		onlineUsers = new list<User>;

		groupInfo = new list<Group>;

		// 连接到数据库
		myDataBase = new ChatDataBase;
		myDataBase->connectToDataBase("group");

		// 获取所有群组的名称
		string groupName[MAX_GROUPS_NUM];
		int groupNum = myDataBase->getGroupNamesFromDataBase(groupName);

		// 遍历所有群组，获取每个群组的成员列表，保存到 groupInfo 链表中
		for (int i = 0; i < groupNum; ++i) {
			Group group;
			group.name = groupName[i];
			group.memberList = new list<GroupUser>;

			string memberListString;// 保存群里所有用户
			myDataBase->getGroupMembersFromDataBase(groupName[i], memberListString);

			int startIndex = 0, endIndex = 0;
			GroupUser groupUser;
			while (1) {
				endIndex = memberListString.find('|', startIndex);
				if (endIndex == -1) {
					break;
				}
				groupUser.name = memberListString.substr(startIndex, endIndex - startIndex);
				group.memberList->push_back(groupUser);
				startIndex = endIndex + 1;
				groupUser.name.clear();
			}
			groupUser.name = memberListString.substr(startIndex, memberListString.size() - startIndex);
			group.memberList->push_back(groupUser);

			groupInfo->push_back(group);

			myDataBase->disconnectToDataBase();

		}
		// 对数据库返回的错误状态进行检查
		if (groupInfo->empty()) {
			cout << "没有找到任何群组成员信息" << endl;
		}
		cout << "成功初始化链表" << endl;

		/*for (list<Group>::iterator it = groupInfo->begin(); it != groupInfo->end(); it++) {
			cout << "群名字：" << it->name << endl;
			for (list<GroupUser>::iterator i = it->l->begin(); i != it->l->end(); i++) {
				cout << i->name << endl;
			}
		}*/

	}
	catch (exception& e) {
		cout << "构造ChatInfo对象出现异常：" << e.what() << endl;
		// 如果在构造函数中出现异常，需要将已经分配的内存释放掉
		if (onlineUsers != nullptr) {
			delete onlineUsers;
			onlineUsers = nullptr;
		}
		if (groupInfo != nullptr) {
			for (auto it = groupInfo->begin(); it != groupInfo->end(); ++it) {
				delete it->memberList;
				it->memberList = nullptr;
			}
			delete groupInfo;
			groupInfo = nullptr;
		}
		if (myDataBase != nullptr) {
			delete myDataBase;
			myDataBase = nullptr;
		}
	}
}

// 析构函数实现
ChatIist::~ChatIist() {
	// 对于指针变量，在使用前进行NULL判断，避免因为空指针而引起的程序崩溃问题
	try {
		if (onlineUsers != nullptr) {
			delete onlineUsers;
			onlineUsers = nullptr;
		}

		if (groupInfo != nullptr) {
			for (auto it = groupInfo->begin(); it != groupInfo->end(); ++it) {
				delete it->memberList;
				it->memberList = nullptr;
			}
			delete groupInfo;
			groupInfo = nullptr;
		}

		if (myDataBase != nullptr) {
			delete myDataBase;
			myDataBase = nullptr;
		}
	}
	catch (exception& e) {
		cout << "析构ChatInfo对象出现异常：" << e.what() << endl;
	}
}
